/**
 * @Title AnswerActivity.java
 * @Package cn.sinokj.party.building.activity
 * @Description TODO(用一句话描述该文件做什么)
 * @author azzbcc Email: azzbcc@sina.com
 * @date 创建时间 2016年7月8日 上午9:52:25
 * @version V1.0
 **/
package cn.sinokj.party.chineseFourParty.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.base.BaseActivity;
import cn.sinokj.party.chineseFourParty.adapter.ViewPagerAdapter;
import cn.sinokj.party.chineseFourParty.bean.ExamChoose;
import cn.sinokj.party.chineseFourParty.bean.ExamQuestion;
import cn.sinokj.party.chineseFourParty.bean.ExamQuestionAnswered;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmInterface;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.NewConfirmDialog;
import cn.sinokj.party.chineseFourParty.view.pop.PopMenu;


/**
 * @author azzbcc Email: azzbcc@sina.com
 * @ClassName AnswerActivity
 * @Description 考试主界面
 * @date 创建时间 2016年7月8日 上午9:52:25
 **/
public class AnswerActivity extends BaseActivity {
    private static final int ANSWER_QUESTION = 1;
    private static final int HANDLE_EXAM = 2;
    @BindView(R.id.title)
    public TextView titleText;
    @BindView(R.id.topbar_left_img)
    public ImageButton topLeftImage;
    @BindView(R.id.topbar_right_text)
    public TextView topRightText;
    @BindView(R.id.answer_view_pager)
    public ViewPager viewPager;
    @BindView(R.id.answer_remain_time)
    public TextView remainTimeText;

    private List<ExamQuestion> examQuestionList;    // 题目Model
    private Map<Integer, ExamQuestionAnswered> examQuestionAnsweredMap;    // 用户选择 Model

    private PopMenu popMenu;
    private boolean examFinish = false;
    private List<String> popItemList = new ArrayList<String>();
    public static Activity answerActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_answer);
        ButterKnife.bind(this);
        answerActivity = this;
        //titleText.setText("单选题");
        /*if (examFinish) {
            titleText.setText("考试");
            topRightText.setText("去交卷");
        } else {
            titleText.setText("查看试题");
            topRightText.setText("答题卡");
        }*/
        titleText.setVisibility(View.VISIBLE);
        topRightText.setVisibility(View.VISIBLE);
        topLeftImage.setVisibility(View.VISIBLE);
        viewPager.setOnPageChangeListener(onPageChangeListener);
        initializeDatas();
        initializeViews();
    }

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int arg0) {
            titleText.setText(examQuestionList.get(arg0).getVcType() + "题");
            remainTimeText.setText(arg0 + 1 + "/" + examQuestionList.size());
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    };

    @SuppressWarnings("unchecked")
    @SuppressLint("UseSparseArrays")
    private void initializeDatas() {
        examFinish = getIntent().getBooleanExtra("examFinish", false);
        if (examFinish) {
            titleText.setText("查看试题");
            topRightText.setText("答题卡");
        } else {
            titleText.setText("考试");
            topRightText.setText("去交卷");
        }
        examQuestionAnsweredMap = new HashMap<Integer, ExamQuestionAnswered>();
        examQuestionList = (List<ExamQuestion>) getIntent().getSerializableExtra("examQuestionList");
        List<ExamQuestionAnswered> examQuestionAnsweredList =
                (List<ExamQuestionAnswered>) getIntent().getSerializableExtra("examQuestionAnsweredList");
        if (examQuestionAnsweredList != null) {
            for (ExamQuestionAnswered examQuestionAnswered : examQuestionAnsweredList) {
                examQuestionAnswered.setSubmit(true);
                examQuestionAnsweredMap.put(examQuestionAnswered.getnTitleId(), examQuestionAnswered);
            }
        }
        for (ExamQuestion examQuestion : examQuestionList) {
            if (examQuestionAnsweredMap.get(examQuestion.getnId()) == null) {
                examQuestionAnsweredMap.put(examQuestion.getnId(), new ExamQuestionAnswered(examQuestion.getnId()));
            }
        }
        remainTimeText.setText("1/" + examQuestionList.size());
    }

    /*
     * 获取第一项未答题的pageId
     */
    public int getFirstNoAnswerItem(String vcType) {
        int item = -1;
        for (int i = 0; i < examQuestionList.size(); i++) {
            ExamQuestion examQuestion = examQuestionList.get(i);
            if (!vcType.contains(examQuestion.getVcType())) {
                continue;
            }
            if (-1 == item) {
                item = i;
            }
            if (!examQuestionAnsweredMap.get(examQuestion.getnId()).isAnswered()) {
                return i;
            }
        }
        return item;
    }

    private PopupWindow.OnDismissListener onDismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            titleText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_down, 0);
        }
    };

    private OnItemClickListener popmenuItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            popMenu.dismiss();
            titleText.setText(popItemList.get(position));
            viewPager.setCurrentItem(getFirstNoAnswerItem(popItemList.get(position)));
        }
    };

    @OnClick({R.id.topbar_left_img, R.id.topbar_right_text, R.id.title, R.id.answer_last_page, R.id.answer_next_page})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.topbar_left_img:
                if (examFinish) {
                    finish();
                } else {
                    DialogShow();
                }
                break;
            case R.id.topbar_right_text:
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < examQuestionAnsweredMap.size(); i++) {
                    if (!examQuestionAnsweredMap.get(examQuestionList.get(i).getnId()).isAnswered()) {
                        stringBuilder.append(i + 1 + ",");
                    }
                }
                if (stringBuilder.length() > 0) {
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                }
                if (stringBuilder.toString() == null || stringBuilder.toString().equals("")) {
                    DialogShow.showRoundProcessDialog(this);
                    handleExamPage();
                } else {
                    Toast.makeText(getApplicationContext(), "第" + stringBuilder.toString() + "题未答", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.title:
               /* popMenu.showAsDropDown(titleText);
                titleText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_up, 0);*/
                break;
            case R.id.answer_last_page:
                lastViewPager();
                break;
            case R.id.answer_next_page:
                nextViewPager();
                break;
        }
    }

    /*
     * 提交试卷
     */
    private void handleExamPage() {
        int item = getFirstSubmit();
        if (-1 == item) {
            DialogShow.closeDialog();
            Intent intent = new Intent(this, AnswerSheetActivity.class);
            intent.putExtra("examFinish", examFinish);
            intent.putExtra("examQuestionList", (Serializable) examQuestionList);
            intent.putExtra("examQuestionAnsweredMap", (Serializable) examQuestionAnsweredMap);
            startActivityForResult(intent, 0);
        } else {
            new Thread(new LoadDataThread(HANDLE_EXAM, item, 0, null)).start();
        }
    }

    /*
     * 上一页
     */
    public void lastViewPager() {
        int currentItem = viewPager.getCurrentItem();
        if (0 == currentItem) {
            Toast.makeText(this, "第一题", Toast.LENGTH_SHORT).show();
            return;
        }
        viewPager.setCurrentItem(currentItem - 1);
    }

    /*
     * 下一页
     */
    public void nextViewPager() {
        int currentItem = viewPager.getCurrentItem();
        if (examQuestionList.size() == currentItem + 1) {
            Toast.makeText(this, "最后一题", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!examQuestionAnsweredMap.get(examQuestionList.get(currentItem).getnId()).isSubmit()) {
            new Thread(new LoadDataThread(ANSWER_QUESTION, currentItem, 0, null)).start();
        }
        viewPager.setCurrentItem(currentItem + 1);
    }

    private void initializeViews() {
        // 初始化弹出菜单
        popMenu = new PopMenu(this);
        Set<String> set = new HashSet<String>();
        for (ExamQuestion examQuestion : examQuestionList) {
            set.add(examQuestion.getVcType() + "题");
        }
        popItemList.addAll(set);
        popMenu.addItems(popItemList);
        popMenu.setOnDismissListener(onDismissListener);
        // 菜单项点击监听器
        popMenu.setOnItemClickListener(popmenuItemClickListener);

        // 初始化选项菜单
        List<View> views = new ArrayList<View>();
        for (ExamQuestion examQuestion : examQuestionList) {
            views.add(getInflateView(examQuestion));
        }
        viewPager.setAdapter(new ViewPagerAdapter(views));
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint({"InflateParams", "ResourceType"})
    public View getInflateView(final ExamQuestion examQuestion) {
        View view = getLayoutInflater().inflate(R.layout.answer_item, null);
        TextView questionText = (TextView) view.findViewById(R.id.answer_item_question);
        //TextView describeText = (TextView) view.findViewById(R.id.answer_item_describe);
        TextView trueAnswerText = (TextView) view.findViewById(R.id.answer_item_true_answer);
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.answer_item_radio_group);
        LinearLayout checkGroup = (LinearLayout) view.findViewById(R.id.answer_item_check_group);
        LinearLayout answerLayout = (LinearLayout) view.findViewById(R.id.answer_item_answer_layout);
        final ExamQuestionAnswered examQuestionAnswered = examQuestionAnsweredMap.get(examQuestion.getnId());
        if (examQuestion.getVcType().contains("单选")) {
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            for (ExamChoose examChoose : examQuestion.getChoices()) {
                RadioButton radioButton = new RadioButton(this);
                radioButton.setLayoutParams(params);
                //去除默认框
                Bitmap a = null;
                radioButton.setButtonDrawable(new BitmapDrawable(a));
                //动态设置选中框的位置和自定义图标
                Drawable myImage = getResources().getDrawable(R.drawable.radio_select_img);
                myImage.setBounds(0, 0, 50, 50);
                radioButton.setCompoundDrawables(null, null, myImage, null);
                radioButton.setBackground(getResources().getDrawable(R.drawable.radio_select_img_test));
                //设置radioButton间距
                radioButton.setPadding(20, 20, 0, 20);
                //设置选择时更改字体颜色
                radioButton.setTextColor(getResources().getColorStateList(R.drawable.color_radiobutton));
                radioButton.setText(examChoose.getVcAnswer());
                radioButton.setTextSize(16);
                radioButton.setTag(examChoose.getVcAnswer().charAt(0));
                radioButton.setClickable(!examFinish);
                radioGroup.addView(radioButton);
                if (examQuestionAnswered.isChoosed(examChoose.getVcAnswer().charAt(0))) {
                    radioGroup.check(radioButton.getId());
                }
            }
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    String choose = group.findViewById(checkedId).getTag().toString();
                    examQuestionAnswered.setSubmit(false);
                    examQuestionAnswered.setVcAnswer(choose);
                    //nextViewPager();

                }
            });
            radioGroup.setVisibility(View.VISIBLE);
            checkGroup.setVisibility(View.GONE);
        } else if (examQuestion.getVcType().contains("多选")) {
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            for (ExamChoose examChoose : examQuestion.getChoices()) {
                CheckBox checkBox = new CheckBox(this);
                checkBox.setLayoutParams(params);
                //去除默认框
                Bitmap a = null;
                checkBox.setButtonDrawable(new BitmapDrawable(a));
                Drawable myImage = getResources().getDrawable(R.drawable.radio_select_img);
                //动态设置选中框的位置和自定义图标
                myImage.setBounds(0, 0, 50, 50);
                checkBox.setCompoundDrawables(null, null, myImage, null);
                checkBox.setBackground(getResources().getDrawable(R.drawable.radio_select_img_test));
                checkBox.setPadding(20, 20, 0, 20);
                //设置选择时更改字体颜色
                checkBox.setTextColor(getResources().getColorStateList(R.drawable.color_radiobutton));
                checkBox.setTextSize(16);
                checkBox.setText(examChoose.getVcAnswer());
                checkBox.setTag(examChoose.getVcAnswer().charAt(0));
                checkBox.setClickable(!examFinish);
                if (examQuestionAnswered.isChoosed(examChoose.getVcAnswer().charAt(0))) {
                    checkBox.setChecked(true);
                }
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        String choose = buttonView.getTag().toString();
                        examQuestionAnswered.setSubmit(false);
                        if (isChecked) {
                            examQuestionAnswered.addVcAnswer(choose);
                        } else {
                            examQuestionAnswered.delVcAnswer(choose);
                        }

                    }
                });
                checkGroup.addView(checkBox);
            }
            radioGroup.setVisibility(View.GONE);
            checkGroup.setVisibility(View.VISIBLE);
        }
        // 只有已完成的考试显示答案解析
        if (examFinish) {
            answerLayout.setVisibility(View.VISIBLE);
        }
        // describeText.setText(examQuestion.getVcDescribe());
        if (examQuestion.getVcAnswer() != null && !examQuestion.getVcAnswer().isEmpty()) {
            trueAnswerText.setText(examQuestion.getVcAnswer().substring(0, examQuestion.getVcAnswer().length() - 1));
        }
        questionText.setText(examQuestion.getnCodeId() + ". " + examQuestion.getVcTitle());
        return view;
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        ExamQuestion examQuestion = examQuestionList.get(arg1);
        return HttpDataService.updateAnswer(
                String.valueOf(examQuestion.getnTopicsId()), String.valueOf(examQuestion.getnId()),
                String.valueOf(examQuestion.getnScore()), examQuestionAnsweredMap.get(examQuestion.getnId()).getVcAnswer());
    }

    private int getFirstSubmit() {
        int result = -1;
        for (int i = 0; i < examQuestionList.size(); i++) {
            ExamQuestion examQuestion = examQuestionList.get(i);
            ExamQuestionAnswered examQuestionAnswered = examQuestionAnsweredMap.get(examQuestion.getnId());
            if (!examQuestionAnswered.isSubmit()) {
                return i;
            }
        }
        return result;
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        ExamQuestion examQuestion = examQuestionList.get(msg.arg1);
        examQuestionAnsweredMap.get(examQuestion.getnId()).setSubmit(true);  // 更改提交状态
        switch (msg.what) {
            case HANDLE_EXAM:
                handleExamPage();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == 0) {
            int nTopicId = data.getIntExtra("nTopicId", 0);
            for (int i = 0; i < examQuestionList.size(); i++) {
                if (examQuestionList.get(i).getnId() == nTopicId) {
                    viewPager.setCurrentItem(i);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 4:
                if (examFinish) {
                    finish();
                } else {
                    DialogShow();
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void DialogShow() {
        NewConfirmDialog.confirmAction(this, null, "确定", "取消", new ConfirmInterface() {
            @Override
            public void onOkButton() {
                finish();
            }

            @Override
            public void onCancelButton() {
            }

            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });

    }
}
